//
//  LLGUserAccount.swift
//  Weibo30LLG
//
//  Created by 李龙 on 16/8/9.
//  Copyright © 2016年 lilong. All rights reserved.
//

import UIKit

class LLGUserAccount: NSObject, NSCoding {

    //用户授权唯一票据
    var access_token: String?
    //生命周期
    var expires_in: NSTimeInterval = 0 {
    
        didSet {
        
            expiresDate = NSDate().dateByAddingTimeInterval(expires_in)
        }
    }
    
    //过期时间
    var expiresDate: NSDate?
    
    //授权用户的UID
    var uid: Int64 = 0
    
    //用户名
    var name: String?
    //头像
    var avatar_large: String?
    
    // MARK: --kvc字典转模型
    init(dict: [String: AnyObject]) {
        
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    // MARK: --防止崩溃
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    override var description: String {
    
        let keys = ["access_token", "expires_in", "uid", "name", "avatar_large"]
        
        return dictionaryWithValuesForKeys(keys).description
    }
    
    // MARK: --归档
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeInt64(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        
    }
    
    // MARK: --解挡
    required init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeInt64ForKey("uid")
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        
    }
    
    // MARK: --存储用户信息
    func saveUserAccount() {
    
        //沙盒路径
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archive")
        
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    // MARK: --读取用户信息
    class func loadUserAccount() -> LLGUserAccount? {
    
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archive")
        
        return NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? LLGUserAccount

    }
    
    
}

/**
*  "access_token" = "2.00qOantC0BUyyu2b9f89cd99WwtLBD";
"expires_in" = 157679999;
"remind_in" = 157679999;
uid = 2656781520;
*/


